package org.codingq92.project.nio_chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * NIO Client端
 *
 * @author: CodingQ92
 * @date: 2025/7/1 21:37
 */
public class NIOChatClient {

    private static final int port = 18000;
    private static Selector selector;
    private static SocketChannel sChannel;

    public static void main(String[] args) {
        try {
            // 1. 创建选择器
            selector = Selector.open();
            // 2. 创建服务器通道 并 链接到server
            sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", port));
            sChannel.configureBlocking(false);
            // 3. 将通道注册到选择器，并监听连接事件
            sChannel.register(selector, SelectionKey.OP_READ);
            // 4.1 开启一个线程读取消息
            new Thread(NIOChatClient::readMsg).start();
            // 4.2 发送消息
            sendMsg();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendMsg() throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请说:");
            String next = scanner.next();
            // 发送数据
            byteBuffer.put(next.getBytes());
            byteBuffer.flip();
            sChannel.write(byteBuffer);
            byteBuffer.clear();
        }
    }

    private static void readMsg() {
        try {
            while (selector.select() > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey next = iterator.next();
                    if (next.isReadable()) {
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        SocketChannel channel = (SocketChannel) next.channel();
                        channel.read(buffer);
                        System.out.println("收到消息: " + new String(buffer.array()).trim());
                    }
                    // 删除当前SelectionKey 否则下次回重复读取
                    iterator.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
